import React from 'react';
import { connect } from 'react-redux';
import BaseComponent from '../../components/common/baseComponent.js';
import Button from '../../components/common/button';
import { not } from '../../utils/validator';
import toast from '../../utils/toast';

@connect(({ loading, invoice }) => {
  return {
    busy: ['invoice/sendEmail'].some(action => loading.effects[action]),
    emailHis: invoice.get('emailHis'),
  };
})
class SendEmail extends BaseComponent {
  state = {
    email: '',
    invoice: null,
  }
  componentDidMount() {
    const { invoice } = this.props.location.state || {};
    if (!invoice) {
      this.props.history.goBack();
    } else {
      this.setState({
        invoice,
        email: invoice.get('email') || '',
      });
      // this.props.dispatch({
      //   type: 'invoice/fetchEmailHis',
      // });
    }
  }

  // componentWillReceiveProps(nextProps) {
  //   if (nextProps.emailHis !== this.props.emailHis) {
  //     const { invoice } = this.state;
  //     const { emailHis } = nextProps;
  //     this.setState({
  //       email: invoice.get('openType') === 1 ? emailHis.get('personal') : emailHis.get('company'),
  //     });
  //   }
  // }

  emailChanged = (e) => {
    this.setState({ email: e.target.value });
  }

  sendEmail = () => {
    const { email, invoice } = this.state;
    if (not('email', email)) {
      toast('请输入正确的邮箱');
    } else {
      this.props.dispatch({
        type: 'invoice/sendEmail',
        payload: {
          email,
          invoiceId: invoice.get('recordId'),
        },
      });
    }
  }

  render() {
    const { email, invoice } = this.state;
    const { busy } = this.props;
    if (!invoice) {
      return null;
    }
    return (
      <div className="send-email-base">
        <div className="content-row">
          <div>电子邮箱</div>
          <input value={email} type="email" onChange={this.emailChanged} maxLength={30} placeholder="请输入收件邮箱" />
        </div>
        <Button title="提交" clickFunc={this.sendEmail} className="send-btn" loading={busy} disabled={not('email', email)} />
      </div>
    );
  }
}

export default SendEmail;
